﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace InputTool
{
    //数据转换类：用于对数据的一些格式进行转换
    //jysh 2008-10-24
    public sealed class XDConvert
    {
        public enum StrType { ASCII = 0, BCD = 1 };
        public enum IntType { HL = 0, LH = 1 }; //HL高位在前，低位在后
        public enum DateType { LEN4 = 0, LEN2 = 1, LEN7 = 2, LEN14 = 3, LEN5 = 4 };	//LEN4 转换为4个字节表示。

        #region 将各种类型转换为字符数组


        //将字符串转换为BYTE数组，ioffset为拷贝到by数组的起始位置 例："31"=0x33,0x31 支持中文字符
        public static void str2ASCII(byte[] by, string str, int iOffset)
        {
            byte[] mbystr = System.Text.Encoding.Default.GetBytes(str);
            byteCopy(mbystr, by, mbystr.Length, 0, iOffset);
        }

        //字符串转换为BCD格式的数组 例："31" = 0x31
        public static void str2BCD(byte[] by, string str, int iOffset)
        {
            int iLen = str.Length;

            if ((iLen % 2) != 0)
                throw new Exception("str2BCD [错误的字符串长度]"); //提供的字符串应该为2的整数倍

            iLen = iLen / 2;

            for (int i = 0; i < iLen; i++)
            {
                by[iOffset + i] = Convert.ToByte(Convert.ToInt16(str.Substring(i * 2, 2), 16));
            }

        }


        //将字符串转换为BYTE数组，ioffset为拷贝到by数组的起始位置 例："31"=0x33,0x31
        public static void str2byte(byte[] by, string str, int ioffset)
        {
            int iL = str.Length;
            char[] chr = str.ToCharArray();
            if (by.Length < ioffset + str.Length)
                throw new Exception("str2byte [索引越界]");

            for (int i = 0; i < iL; i++)
            {
                if (chr[i] > 255)
                {
                    by[ioffset] = Convert.ToByte(chr[i] / 256);
                    ioffset++;
                    by[ioffset] = Convert.ToByte(chr[i] % 256);
                    ioffset++;
                }
                else
                {
                    by[ioffset] = Convert.ToByte(chr[i]);
                    ioffset++;
                }

            }

        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteHL(string str, int iLen)
        {
            UInt32 iTemp = Convert.ToUInt32(str);

            return int2ByteHL(iTemp, iLen);
        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteHL(int iTemp, int iLen)
        {
            return int2ByteHL((UInt32)iTemp, iLen);
        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteHL(UInt32 iTemp, int iLen)
        {
            byte[] byTemp = System.BitConverter.GetBytes(iTemp);

            byte[] byResult = new byte[iLen];
            for (int i = 0; i < iLen; i++)
            {
                byResult[iLen - i - 1] = byTemp[i];
            }

            return byResult;
        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteLH(string str, int iLen)
        {
            UInt32 iTemp = Convert.ToUInt32(str);

            return int2ByteLH(iTemp, iLen);
        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteLH(int iTemp, int iLen)
        {
            return int2ByteLH((UInt32)iTemp, iLen);
        }

        //Int转换为高位在前低位在后的Hex 17666 -> 0x4502
        public static byte[] int2ByteLH(UInt32 iTemp, int iLen)
        {
            byte[] byTemp = System.BitConverter.GetBytes(iTemp);

            return byTemp;
        }

        #region 各种类型转换为数组
      
      
        /// <summary>
        /// 转换成Byte数组
        /// 1:  BCD方式例："31" = 0x31 .其他 字符串例："31"=0x33 0x31
        /// </summary>
        /// <param name="by">需要转换到的数组</param>
        /// <param name="iOffset">数组中的编译地址</param>
        /// <param name="str">需要转的数据</param>
        /// <param name="iType">转换的类型.</param>
        public static void Convert2Byte(byte[] by, int iOffset, string str, StrType iType)
        {
            if (iType == StrType.BCD)
                str2BCD(by, str, iOffset);
            else
                str2ASCII(by, str, iOffset);

        }
     
        /// <summary>
        /// 转换成Byte数组
        /// </summary>
        /// <param name="by">需要转换到的数组</param>
        /// <param name="iOffset">数组中的编译地址</param>
        /// <param name="iTemp">需要转的数据</param>
        /// <param name="iLen">需要转换的长度</param>
        /// <param name="iType">转换的类型.</param>
        public static void Convert2Byte(byte[] by, int iOffset, UInt32 iTemp, int iLen, IntType iType)
        {
            if (iType == IntType.HL)
            {
                byte[] mby = int2ByteHL(iTemp, iLen);
                byteCopy(mby, by, iLen, 0, iOffset);
            }
            else
            {
                byte[] mby = int2ByteLH(iTemp, iLen);
                byteCopy(mby, by, iLen, 0, iOffset);
            }
        }

        /// <summary>
        /// 转换成Byte数组
        /// </summary>
        /// <param name="by">需要转换到的数组</param>
        /// <param name="iOffset">数组中的编译地址</param>
        /// <param name="iTemp">需要转的数据</param>
        /// <param name="iLen">需要转换的长度</param>
        /// <param name="iType">转换的类型.</param>
        public static void Convert2Byte(byte[] by, int iOffset, int iTemp, int iLen, IntType iType)
        {
            if (iType == IntType.HL)
            {
                byte[] mby = int2ByteHL(iTemp, iLen);
                byteCopy(mby, by, iLen, 0, iOffset);
            }
            else
            {
                byte[] mby = int2ByteLH(iTemp, iLen);
                byteCopy(mby, by, iLen, 0, iOffset);
            }

        }


        /// <summary>
        /// 转换成Byte数组
        /// </summary>
        /// <param name="by">需要转换到的数组</param>
        /// <param name="iOffset">数组中的编译地址</param>
        /// <param name="dtIn">需要转换日期</param>
        /// <param name="iType">转换的日期类型.</param>
        public static void Convert2Byte(byte[] by, int iOffset, DateTime dtIn, DateType iType)
        {
            UInt32 iTemp = 0;
            int iLen = 0;
            string strTemp;

            DateTime dtTemp;
            TimeSpan tsTemp;
            switch (iType)
            {
                case DateType.LEN2:
                    dtTemp = new DateTime(1899, 12, 31);
                    tsTemp = dtIn.Subtract(dtTemp);
                    iTemp = Convert.ToUInt32(tsTemp.Days);
                    iLen = 2;
                    Convert2Byte(by, iOffset, iTemp, iLen, IntType.HL);
                    break;
                case DateType.LEN4:
                    dtTemp = new DateTime(1970, 1, 1);
                    tsTemp = dtIn.Subtract(dtTemp);
                    iTemp = Convert.ToUInt32(tsTemp.TotalSeconds);
                    iLen = 4;
                    Convert2Byte(by, iOffset, iTemp, iLen, IntType.HL);
                    break;
                case DateType.LEN7:
                    strTemp = dtIn.ToString("yyyyMMddHHmmss");
                    Convert2Byte(by, iOffset, strTemp, StrType.BCD);
                    break;
                case DateType.LEN14:
                    strTemp = dtIn.ToString("yyyyMMddHHmmss");
                    Convert2Byte(by, iOffset, strTemp, StrType.ASCII);
                    break;
                case DateType.LEN5:
                    byte[] byTmp = Date2ByteMSM(dtIn);
                    byteCopy(byTmp, by, 5, 0, iOffset);
                    break;
            }

        }
        #endregion

        /// <summary> 
        /// 将MSM格式的字节数组转换为字符串格式的时间。
        /// </summary> 
        /// <param name="dt">日期</param> 
        /// <returns>MSM型字符串</returns>
        public static byte[] Date2ByteMSM(DateTime dt)
        {
            byte[] byTmp = new byte[5];
            byte[] byTmp2 = new byte[4];

            //      DateTime dt = new DateTime();
            //     dt = Convert.ToDateTime("2000-03-01 09:30:10");
            //    dt = DateTime.Now;

            int iTmp, iTmp2;
            iTmp = dt.Year;
            iTmp2 = iTmp << 4;

            iTmp = dt.Month;
            iTmp2 += iTmp;

            Convert2Byte(byTmp, 0, iTmp2, 2, IntType.HL);

            iTmp = dt.Day;
            iTmp2 = iTmp << (2 + 6 + 6 + 5);

            iTmp = dt.Hour;
            iTmp = iTmp << (2 + 6 + 6);
            iTmp2 += iTmp;

            iTmp = dt.Minute;
            iTmp = iTmp << (2 + 6);
            iTmp2 += iTmp;

            iTmp = dt.Second;
            iTmp = iTmp << (2);
            iTmp2 += iTmp;
            Convert2Byte(byTmp2, 0, iTmp2, 4, IntType.HL);

            byteCopy(byTmp2, byTmp, 3, 1, 2);

            return byTmp;
        }

        #endregion

        #region 将字符串转换为定长(后面补空格)
        /// <summary>
        /// 将Str转换为定长字符串,长度不够后面补空格(支持中英文)
        /// <param name="iNum">要格式化的长度</param> 
        /// <param name="istr">要格式化的数据</param> 
        /// </summary>
        public static string FormatBlank(int iNum, string str)
        {
            int myLength = (System.Text.Encoding.Default.GetBytes(str)).Length;

            while (myLength < iNum)
            {
                str += " ";
                myLength = (System.Text.Encoding.Default.GetBytes(str)).Length;

            }
            if (myLength > iNum)
                throw new Exception(string.Format("将字符串{0}格式化为{1}长时,发生溢出错误", str, iNum.ToString()));

            return str;
        }

        /// <summary>
        /// 将Int转换为定长字符串,长度不够后面补空格
        /// <param name="iNum">要格式化的长度</param> 
        /// <param name="istr">要格式化的数据</param> 
        /// </summary>
        public static string FormatBlank(int iNum, int istr)
        {
            string str = istr.ToString();

            while (str.Length < iNum)
            {
                str += " ";
            }
            if (str.Length > iNum)
                throw new Exception(string.Format("将数值{0}格式化为{1}长时,发生溢出错误", istr.ToString(), iNum.ToString()));


            return str;
        }
        #endregion

        public static string int2strMoney(int iMoney)
        {
            string strTmp = iMoney.ToString();
            while (strTmp.Length < 3)
                strTmp = "0" + strTmp;

            string strMoney;
            strMoney = strTmp.Substring(0, strTmp.Length - 2);
            strMoney += "." + strTmp.Substring(strTmp.Length - 2, 2);

            return strMoney;
        }
        /// <summary> 
        /// 将MSM格式的字节数组转换为字符串格式的时间。
        /// jysh 2008-09-29 修改
        /// </summary> 
        /// <param name="byTime">7D 03 0A 5E 28H</param> 
        /// <returns>20000301093010</returns>
        public static string MSM2StrDate(byte[] byTime)
        {
            string str = "";
            uint iTime;
            uint iTemp;

            iTime = Convert.ToUInt32(byTime[0] * 256 * 256 * 256 + byTime[1] * 256 * 256);

            iTemp = iTime >> (32 - 12);
            str = str + iTemp.ToString("0000"); //年

            iTemp = iTime << (12);
            iTemp = iTemp >> (32 - 4);
            str = str + iTemp.ToString("00");   //月

            //jysh 2008-09-29 修改
            iTime = Convert.ToUInt32(byTime[2] * 256 * 256 + byTime[3] * 256 + byTime[4]);
            iTemp = iTime >> (32 - 5 - 8);
            str = str + iTemp.ToString("00"); //日

            iTemp = iTime << (5 + 8);
            iTemp = iTemp >> (32 - 5);
            str = str + iTemp.ToString("00");   //时

            iTemp = iTime << (5 + 5 + 8);
            iTemp = iTemp >> (32 - 6);
            str = str + iTemp.ToString("00");   //分

            iTemp = iTime << (5 + 5 + 6 + 8);
            iTemp = iTemp >> (32 - 6);
            str = str + iTemp.ToString("00");   //秒

            return str;

        }

        //将MCM格式的字节数组转换为字符串格式的时间。79D96D19H －》"20300712225225"
        public static string MCM2StrDate(byte[] byTime)
        {

            uint iTemp;

            iTemp = Convert.ToUInt32(byTime[0] * 256 * 256 * 256 + byTime[1] * 256 * 256 + byTime[2] * 256 + byTime[3]);
            return MCM2StrDate(iTemp);
        }

        public static string MCM2StrDateLH(byte[] byTime)
        {

            uint iTemp;

            iTemp = Convert.ToUInt32(byTime[3] * 256 * 256 * 256 + byTime[2] * 256 * 256 + byTime[1] * 256 + byTime[0]);
            return MCM2StrDate(iTemp);
        }

        public static string MCM2StrDate(uint iTime)
        {
            string str = "20";
            uint iTemp;

            iTemp = iTime >> (32 - 6);
            str = str + iTemp.ToString("00");
            iTemp = iTime << (6);
            iTemp = iTemp >> (32 - 4);
            str = str + iTemp.ToString("00");
            iTemp = iTime << (6 + 4);
            iTemp = iTemp >> (32 - 5);
            str = str + iTemp.ToString("00");
            iTemp = iTime << (6 + 4 + 5);
            iTemp = iTemp >> (32 - 5);
            str = str + iTemp.ToString("00");
            iTemp = iTime << (6 + 4 + 5 + 5);
            iTemp = iTemp >> (32 - 6);
            str = str + iTemp.ToString("00");
            iTemp = iTime << (6 + 4 + 5 + 5 + 6);
            iTemp = iTemp >> (32 - 6);
            str = str + iTemp.ToString("00");

            return str;
        }

        //将HEX格式的字符串转换成INT bHL:高位在前 
        //StrHex2int( "00000012",true) = 0x12;StrHex2int( "00000012",flase) = 0x12000000
        public static bool StrHex2int(string strHex, bool bHL, out Int32 iOut)
        {
            if (strHex.Length == 0)
                iOut = 0;

            if (!bHL)
            {

                if ((strHex.Length % 2) == 1)
                    strHex = "0" + strHex;
                string strT = strHex;
                strHex = "";
                for (int i = strT.Length - 2; i > -1; i = i - 2)
                {
                    strHex += strT.Substring(i, 2);
                    strT = strT.Substring(0, i);
                }
            }
            try
            {
                iOut = Convert.ToInt32(strHex, 16);
            }
            catch (Exception ex)
            {
                iOut = 0;
                return false;
            }

            return true;
        }

        //将HEX格式的字符串转换成INT bHL:高位在前 
        //StrHex2int( "00000012",true) = 0x12;StrHex2int( "00000012",false) = 0x12000000
        public static bool StrHex2int(string strHex, bool bHL, out UInt32 iOut)
        {
            if (strHex.Length == 0)
                iOut = 0;

            if (!bHL)
            {

                if ((strHex.Length % 2) == 1)
                    strHex = "0" + strHex;
                string strT = strHex;
                strHex = "";
                for (int i = strT.Length - 2; i > -1; i = i - 2)
                {
                    strHex += strT.Substring(i, 2);
                    strT = strT.Substring(0, i);
                }
            }
            try
            {
                iOut = Convert.ToUInt32(strHex, 16);
            }
            catch (Exception ex)
            {
                iOut = 0;
                return false;
            }

            return true;
        }

        //异或 将一个Byte数组的最后一个字节设置成，前面所有字节的异或和
        public static void XORArry(byte[] bt)
        {
            byte[] btTemp = new byte[8];
            int iTemp = 0;
            for (int i = 0; i < bt.Length - 1; i++)
            {
                iTemp = iTemp ^ (int)bt[i];
            }
            btTemp = System.BitConverter.GetBytes(iTemp);
            bt[bt.Length - 1] = btTemp[0];


        }


        //异或
        public static void XORArry(byte[] bt, int nLen)
        {
            byte[] btTemp = new byte[8];
            int iTemp = 0;
            for (int i = 0; i < nLen; i++)
            {
                iTemp = iTemp ^ (int)bt[i];
            }
            btTemp = System.BitConverter.GetBytes(iTemp);
            bt[nLen] = btTemp[0];


        }

        //字符串转换为BCD格式的数组 例："31" = 0x31
        public static void str2BCDbyte(byte[] by, string str, int iOffset)
        {
            int iLen = str.Length;
            iLen = iLen / 2;
            for (int i = 0; i < iLen; i++)
            {
                by[iOffset + i] = Convert.ToByte(Convert.ToInt16(str.Substring(i * 2, 2), 16));
            }

        }

        //数组拷贝
        public static void byteCopy(byte[] byS, byte[] byD, int iLen, int iSOffset, int iDOffset)
        {
            for (int i = 0; i < iLen; i++)
            {
                byD[i + iDOffset] = byS[i + iSOffset];
            }
        }

        //高位在前，低位在后 数组拷贝
        public static void byteCopyHL(byte[] byS, byte[] byD, int iLen, int iSOffset, int iDOffset)
        {
            for (int i = 0; i < iLen; i++)
            {
                byD[i + iDOffset] = byS[iLen - i - 1 + iSOffset];
            }

        }

        //其实就是：FormatZero(iNum,0)
        private string GetNumZero(int iNum)
        {
            string iTemp = "";
            for (int i = 0; i < iNum; i++)
            {
                iTemp = "0" + iTemp;
            }
            return iTemp;
        }
        /// <summary>
        /// 字符串比较
        /// <param name="by1">数据A</param>
        /// <param name="by2">数据B</param>
        /// <param name="nLen">要比较的长度</param> 
        /// <returns>True：相等，False：不等</returns>
        /// </summary>
        public static bool CompareArry(byte[] by1, byte[] by2, int nLen)
        {
            for (int i = 0; i < nLen; i++)
            {
                if (by1[i] != by2[i])
                    return false;
            }
            return true;

        }

        public static UInt32 byte2UIntLH(byte[] by)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < by.Length; i++)
                mby[i] = by[i];

            return System.BitConverter.ToUInt32(mby, 0);
        }

        //将Str格式为固定长度的字符串。例: FormatZero(8,"7")="00000007"
        public static string FormatZero(int iNum, string str)
        {

            while (str.Length < iNum)
            {
                str = "0" + str;
            }
            if (str.Length > iNum)
                str = str.Substring(0, iNum);

            return str;
        }

        //将Int格式为固定长度的字符串。例: FormatZero(8,7)="00000007"
        public static string FormatZero(int iNum, int istr)
        {
            string str = istr.ToString();

            while (str.Length < iNum)
            {
                str = "0" + str;
            }
            if (str.Length > iNum)
                str = str.Substring(0, iNum);

            return str;
        }

        //将Int格式为固定长度的字符串。例: FormatZero(8,7)="00000007"
        public static string FormatZero(int iNum, uint istr)
        {
            return FormatZero(iNum, Convert.ToInt32(istr));
        }

        /// <summary>
        /// 将字符串转换成16进制的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string str_To_strH(string str)
        {
            string strH = string.Empty;

            foreach (char ch in str)
            {
                string ss = Convert.ToString(ch, 16);
                if (ss.Length == 1)
                {
                    ss = "0" + ss;
                }
                strH += ss;
            }

            return strH;
        }

        #region     int与string的转移

        /// <summary>
        /// Int转为16进制的字符串只支持一位
        /// <param name="iTmp">12</param>
        /// <returns>C
        private static string specInttoString(int source)//被主要方法调用的一个辅助方法
        {

            if (source < 10)
            {

                return source.ToString();
            }
            else
            {
                switch (source)
                {

                    case 10:

                        return "A";

                    case 11:

                        return "B";

                    case 12:

                        return "C";

                    case 13:

                        return "D";

                    case 14:

                        return "E";

                    case 15:

                        return "F";

                    default:

                        return "";

                }

            }
        }

        /// <summary>
        /// Int转为16进制的字符串只支持一个字节
        /// <param name="iTmp">0x80</param>
        /// <returns>80
        public static string Int2StrBCD(int iData)
        {
            string strTmp;
            int iTmp = iData / 16;
            strTmp = specInttoString(iTmp);

            iTmp = iData % 16;
            strTmp += specInttoString(iTmp);

            return strTmp;
        }

        /// <summary>
        /// Int转为16进制的字符串低位在前，高位在后
        /// <param name="iData">0x80</param>
        /// <returns>80
        public static string Int2StrBCD(int iData, int iLen)
        {
            byte[] byTmp = new byte[4];
            Convert2Byte(byTmp, 0, iData, iLen, IntType.LH);

            string strTmp = XDConvert.HexAscArr2Str(byTmp);


            return strTmp;
        }

        #endregion
        #region Hex与Hexbin的转换
        public static void Hexbin2Hex(byte[] bHexbin, byte[] bHex, int nLen)
        {
            for (int i = 0; i < nLen / 2; i++)
            {
                if (bHexbin[2 * i] < 0x41)
                {
                    bHex[i] = Convert.ToByte(((bHexbin[2 * i] - 0x30) << 4) & 0xf0);
                }
                else
                {
                    bHex[i] = Convert.ToByte(((bHexbin[2 * i] - 0x37) << 4) & 0xf0);
                }

                if (bHexbin[2 * i + 1] < 0x41)
                {
                    bHex[i] |= Convert.ToByte((bHexbin[2 * i + 1] - 0x30) & 0x0f);
                }
                else
                {
                    bHex[i] |= Convert.ToByte((bHexbin[2 * i + 1] - 0x37) & 0x0f);
                }
            }
        }
        public static byte[] Hexbin2Hex(byte[] bHexbin, int nLen)
        {
            if (nLen % 2 != 0)
                return null;
            byte[] bHex = new byte[nLen / 2];
            Hexbin2Hex(bHexbin, bHex, nLen);
            return bHex;
        }
        public static void Hex2Hexbin(byte[] bHex, byte[] bHexbin, int nLen)
        {
            byte c;
            for (int i = 0; i < nLen; i++)
            {
                c = Convert.ToByte((bHex[i] >> 4) & 0x0f);
                if (c < 0x0a)
                {
                    bHexbin[2 * i] = Convert.ToByte(c + 0x30);
                }
                else
                {
                    bHexbin[2 * i] = Convert.ToByte(c + 0x37);
                }
                c = Convert.ToByte(bHex[i] & 0x0f);
                if (c < 0x0a)
                {
                    bHexbin[2 * i + 1] = Convert.ToByte(c + 0x30);
                }
                else
                {
                    bHexbin[2 * i + 1] = Convert.ToByte(c + 0x37);
                }
            }
        }
        public static byte[] Hex2Hexbin(byte[] bHex, int nLen)
        {
            byte[] bHexbin = new byte[nLen * 2];
            Hex2Hexbin(bHex, bHexbin, nLen);
            return bHexbin;
        }

        public static byte[] strH_to_B(string hex)
        {
            hex = hex.Trim();
            byte[] bt;
            int hexlen;

            hexlen = hex.Length / 2;
            bt = new byte[hexlen];
            for (int i = 0; i < hexlen; i++)
            {
                bt[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
            return bt;
        }

        public static byte[] strH_to_B(string hex, int nLen)
        {
            hex = hex.Trim();
            byte[] bt;
            int hexlen;

            hexlen = hex.Length / 2;
            bt = new byte[nLen + 4];
            for (int i = 0; i < nLen; i++)
            {
                bt[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
            return bt;
        }

        #endregion


        #region 数组和字符串之间的转化


        /// <summary> 
        /// 比较两个数组是否相等
        /// </summary> 
        /// <param name="by1">数组1</param> 
        /// <param name="by2">数组2</param> 
        /// <param name="iLen">要比较的长度</param> 
        /// <returns>True:相等；False:不相等</returns>
        public static bool CompareByte(byte[] by1, byte[] by2, int iLen)
        {
            for (int i = 0; i < iLen; i++)
            {
                if (by1[i] != by2[i])
                    return false;
            }
            return true;
        }

        public static byte[] Str2Arr(String s)
        {
            return (new UnicodeEncoding()).GetBytes(s);
        }
        public static string Arr2Str(byte[] buffer)
        {
            return (new UnicodeEncoding()).GetString(buffer, 0, buffer.Length);
        }

        public static byte[] Str2AscArr(String s)
        {
            return System.Text.UnicodeEncoding.Convert(System.Text.Encoding.Unicode,
            System.Text.Encoding.ASCII,
            Str2Arr(s));
        }

        public static byte[] Str2HexAscArr(String s)
        {
            byte[] hex = Str2AscArr(s);
            byte[] hexbin = Hex2Hexbin(hex, hex.Length);
            return hexbin;
        }
        public static string AscArr2Str(byte[] b)
        {
            return System.Text.UnicodeEncoding.Unicode.GetString(
            System.Text.ASCIIEncoding.Convert(System.Text.Encoding.ASCII,
            System.Text.Encoding.Unicode,
            b)
            );
        }
        public static string AscArr2CnStr(byte[] b)
        {
            return System.Text.UnicodeEncoding.Unicode.GetString(
            System.Text.ASCIIEncoding.Convert(System.Text.Encoding.Unicode,
            System.Text.Encoding.Unicode,
            b)
            );
        }

        //0x01,0x45 转化为："012D"
        public static string HexAscArr2Str(byte[] buffer)
        {
            byte[] b = Hex2Hexbin(buffer, buffer.Length);
            return AscArr2Str(b);
        }

        public static string HexAscArr2Str(byte[] buffer, int iLen)
        {
            byte[] b = Hex2Hexbin(buffer, iLen);
            return AscArr2Str(b);
        }

        public static int byte2int(byte[] by)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < by.Length; i++)
                mby[i] = by[i];

            return System.BitConverter.ToInt32(mby, 0);
        }


        /// <summary>
        /// BYTE数组转为Int类型
        /// </summary>
        /// <param name="bySource">需要转换的数组</param>
        /// <param name="iOffset">转换的开始偏移地址</param>
        /// <returns>转换完成的Int类型</returns>
        public static int Byte2Int(byte[] bySource,int iOffset)
        {
            int nSize = 4;
            if (nSize > bySource.Length) nSize = bySource.Length;

            return Byte2Int(bySource, iOffset, nSize);
        }

        /// <summary>
        /// BYTE数组转为Int类型
        /// </summary>
        /// <param name="bySource">需要转换的数组</param>
        /// <param name="iOffset">转换的开始偏移地址</param>
        /// <param name="iLen">要转换的字节</param>
        /// <returns>转换完成的Int类型</returns>
        public static int Byte2Int(byte[] by, int iOffset, int iLen)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < iLen; i++)
                mby[i] = by[i + iOffset];

            return System.BitConverter.ToInt32(mby, 0);
        }


        /// <summary>
        /// 数据组转Int型(高位在前,低位在后) 
        /// <param name="by">数组</param>
        /// <param name="iOffset">偏移地址</param>
        /// <param name="iLen">数组长度</param>
        ///  <returns>Int型值</returns>
        /// </summary>
        public static int byte2intHL(byte[] by, int iOffset, int iLen)
        {
            byte[] mby = new byte[4];
            byteCopy(by, mby, iLen, iOffset, 0);

            return byte2intHL(mby);
        }

        /// <summary>
        /// 对数组中的int型加值
        /// <param name="by">数组</param>
        /// <param name="iOffset">偏移地址</param>
        /// <param name="iLen">数组长度</param>
        /// <param name="iNum">增加值</param>  
        /// </summary>
        public static void byteArrayAdd(byte[] by, int iOffset, int iLen, int iNum)
        {
            byte[] mby = new byte[2];
            byteCopy(by, mby, iLen, iOffset, 0);

            int iVal = byte2intHL(mby);
            iVal += iNum;
            Convert2Byte(by, iOffset, iVal, iLen, IntType.HL);
        }

        /// <summary>
        /// 对数组中的int型加值
        /// <param name="by">数组</param>
        /// <param name="iOffset">偏移地址</param>
        /// <param name="iLen">数组长度</param>
        /// <param name="iNum">增加值</param>  
        /// </summary>
        public static void byteArrayDec(byte[] by, int iOffset, int iLen, int iNum)
        {
            byte[] mby = new byte[4];
            byteCopy(by, mby, iLen, iOffset, 0);

            int iVal = byte2intHL(mby);
            iVal -= iNum;
            Convert2Byte(by, iOffset, iVal, iLen, IntType.HL);
        }


        public static UInt32 byte2uint(byte[] by)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < by.Length; i++)
                mby[i] = by[i];

            return System.BitConverter.ToUInt32(mby, 0);
        }

        //如果by的长度不等于4将会是个错误。
        public static int byte2intHL(byte[] by)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < by.Length; i++)
                mby[by.Length - 1 - i] = by[i];

            return System.BitConverter.ToInt32(mby, 0);
        }

        /// <summary>
        /// 将高位在前低位在后的数组转为无符合整型。
        /// </summary>
        /// <returns>获得的文本,若操作失败则返回空对象</returns>
        public static UInt32 byte2uintHL(byte[] by)
        {
            byte[] mby = new byte[4];

            for (int i = 0; i < by.Length; i++)
                mby[by.Length - 1 - i] = by[i];

            return System.BitConverter.ToUInt32(mby, 0);
        }

        public static string Format2Date(string str)
        {
            if (str.Length != 14)
                return "";

            string strTemp;
            strTemp = str.Substring(0, 4) + "-";
            strTemp += str.Substring(4, 2) + "-";
            strTemp += str.Substring(6, 2) + " ";
            strTemp += str.Substring(8, 2) + ":";
            strTemp += str.Substring(10, 2) + ":";
            strTemp += str.Substring(12, 2);
            return strTemp;

        }

        /// <summary>
        /// 将钱包格式字符串由分转化为元
        /// </summary>
        /// <returns>以元为单位的字符串（带小数点）</returns>
        public static string Format2Money(string str)
        {
            string strTemp;
            while (str.Length < 3)
                str = "0" + str;

            strTemp = str.Substring(0, str.Length - 2);
            strTemp += ".";
            strTemp += str.Substring(str.Length - 2, 2);
            strTemp += "元";
            return strTemp;

        }
        /// <summary>
        /// 将钱包格式字符串由分转化为元带“元”
        /// </summary>
        /// <returns>以元为单位的字符串（带小数点）</returns>
        public static string Format2Money(int iMoney)
        {
            string str = iMoney.ToString();
            string strTemp;
            while (str.Length < 3)
                str = "0" + str;

            strTemp = str.Substring(0, str.Length - 2);
            strTemp += ".";
            strTemp += str.Substring(str.Length - 2, 2);
            strTemp += "元";
            return strTemp;

        }


        /// <summary>
        /// 将钱包格式字符串由分转化为元不带“元”
        /// </summary>
        /// <returns>以元为单位的字符串（带小数点）</returns>
        public static string Format2Money2(int  iValue)
        {
            string str = iValue.ToString();
            string strTemp;
            while (str.Length < 3)
                str = "0" + str;

            strTemp = str.Substring(0, str.Length - 2);
            strTemp += ".";
            strTemp += str.Substring(str.Length - 2, 2);          
            return strTemp;

        }

        /// <summary>
        /// 将钱包格式字符串由分转化为元不带“元”
        /// </summary>
        /// <returns>以元为单位的字符串（带小数点）</returns>
        public static string Format2Money2(string str)
        {
            int iVal = Convert.ToInt32(str);
            return Format2Money2(iVal);
            
            string strTemp;
            while (str.Length < 3)
                str = "0" + str;

            strTemp = str.Substring(0, str.Length - 2);
            strTemp += ".";
            strTemp += str.Substring(str.Length - 2, 2);
            return strTemp;

        }
        #endregion


        #region 序列化
        ///   <summary>   
        ///   序列化为二进制字节数组   
        ///   </summary>   
        ///   <param   name="request">要序列化的对象</param>   
        ///   <returns>字节数组</returns>   
        public static byte[] SerializeBinary(object request)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            serializer.Serialize(memStream, request);
            return memStream.GetBuffer();
        }

        ///   <summary>   
        ///   序列化为二进制字节数组   
        ///   </summary>   
        ///   <param   name="request">要序列化的对象</param>   
        ///   <returns>字节数组</returns>   
        public static string SerializeStr(object request)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            serializer.Serialize(memStream, request);

            return HexAscArr2Str(memStream.GetBuffer());
        }

        ///   <summary>   
        ///   从二进制数组反序列化得到对象   
        ///   </summary>   
        ///   <param   name="buf">字节数组</param>   
        ///   <returns>得到的对象</returns>   
        public static object DeserializeBinary(byte[] buf)
        {
            System.IO.MemoryStream memStream = new MemoryStream(buf);
            memStream.Position = 0;
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =
            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            object newobj = deserializer.Deserialize(memStream);
            memStream.Close();
            return newobj;
        }

        ///   <summary>   
        ///   从二进制数组反序列化得到对象   
        ///   </summary>   
        ///   <param   name="buf">字节数组</param>   
        ///   <returns>得到的对象</returns>   
        public static object DeserializeStr(string str)
        {

            System.IO.MemoryStream memStream = new MemoryStream(Str2HexAscArr(str));
            memStream.Position = 0;
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =
            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            object newobj = deserializer.Deserialize(memStream);
            memStream.Close();
            return newobj;
        }
        #endregion
    }

}
